<?php

namespace App\Http\Controllers\Sessions;

use App\Http\Controllers\Controller;
use App\Http\Requests\SessionGetRequest;
use App\Http\Requests\SessionOpenPageRequest;
use App\Http\Requests\SessionRequest;
use App\Models\ConnectionsTypesModel;
use App\ViewModels\ConnectionsViewModel;
use Illuminate\Http\Request;

class SessionController extends Controller
{
    public function openPage(SessionOpenPageRequest $request)
    {
        return view('server.opensession', ['title' => 'Создать сессию',
            'connection' => $request->get('connection'),
            'ip' => $request->get('server_ip'),
            'user' => $request->get('user_id')]);
    }

    public function open(SessionRequest $request)
    {
        $parameters = json_decode(ConnectionsViewModel::make()->getAllConnectionRulesByName($request->get('connection')), true);
        $connectionParameters = [];
        foreach ($parameters as $parameter => $val) {
            $connectionParameters[$parameter] = $request->get($parameter);
        }
        $request->user()->sessions()->create([
            'server' => $request->get('server_ip'),
            'start_time' => time(),
            'active' => true,
            'end_time' => null,
            'connection_id' => ConnectionsTypesModel::query()
                ->where('connection', '=', $request->get('connection'))
                ->first()
                ->id,
            'parameters' => json_encode($connectionParameters),
        ]);

        return redirect()->route('server.session', ['ip' => $request->get('server_ip'), 'connection' => $request->get('connection')]);
    }

    public function close(Request $request)
    {
        $request->user()->sessions()
            ->where('active', '=', true)
            ->where('server', '=', $request->get('server_ip'))
            ->first()
            ->close()
            ->save();

        return redirect()->route('servers.list');
    }

    public function get(SessionGetRequest $request)
    {
        return redirect()->route('server.session', ['ip' => $request->get('server_ip'),
            'connection' => $request->get('connection')]);
    }
}
